<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 简单的自动曝光、平均像素值（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>一个图像有n个像素点&#xff0c;存储在一个长度为n的数组img里&#xff0c;每个像素点的取值范围[0,255]的正整数。<br /> 请你给图像每个像素点值加上一个整数k&#xff08;可以是负数&#xff09;&#xff0c;得到新图newImg&#xff0c;使得新图newImg的所有像素平均值最接近中位值128。<br /> 请输出这个整数k。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>n个整数&#xff0c;中间用空格分开</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>一个整数k</p> 
<p></p> 
<h4>备注</h4> 
<p>• 1 &lt;&#61; n &lt;&#61; 100<br /> • 如有多个整数k都满足&#xff0c;输出小的那个k&#xff1b;<br /> • 新图的像素值会自动截取到[0,255]范围。当新像素值&lt;0&#xff0c;其值会更改为0&#xff1b;当新像素值&gt;255&#xff0c;其值会更改为255&#xff1b;</p> 
<p>例如newImg&#61;”-1 -2 256″,会自动更改为”0 0 255″</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">0 0 0 0</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">128</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">四个像素值都为0</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">129 130 129 130</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">-2</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">-1的均值128.5&#xff0c;-2的均值为127.5&#xff0c;输出较小的数-2</td></tr></tbody></table> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>本题如果用暴力法求解的话思路如下&#xff1a;</p> 
<p>首先输入的老图片的像素值&#xff0c;应该是符合要求的&#xff0c;即像素点应都在[0,255]范围内&#xff0c;因此像素点最小值为0&#xff0c;最大值为255。</p> 
<p>那么如果我们想让0接近中位值128&#xff0c;则需要加上128。</p> 
<p>如果我们想让255接近中位值128&#xff0c;则需要减去127。</p> 
<p>因此&#xff0c;k的取值范围应该在-127到128之间&#xff0c;这样的话&#xff0c;就可以保证每一个点都能接近到中位值。</p> 
<p>那么我们就从-127遍历到128&#xff0c;然后将遍历值加到老图片的每一个像素值上&#xff0c;然后求平均值。</p> 
<p>需要注意的是&#xff0c;如果新图片的像素点值低于0&#xff0c;则取0&#xff0c;高于255&#xff0c;则取255</p> 
<pre><code class="language-javascript">function getResult(arr) {
  const ans &#61; [];
  for (let k &#61; -127; k &lt;&#61; 128; k&#43;&#43;) {
    const res &#61;
      arr
        .map((num) &#61;&gt; {
          const newNum &#61; num &#43; k;
          return newNum &lt; 0 ? 0 : newNum &gt; 255 ? 255 : newNum;
        })
        .reduce((p, c) &#61;&gt; p &#43; c) / arr.length;
    ans.push([k, res]);
  }
  console.table(ans);
}

getResult([10, 20, 100, 200, 250]);
</code></pre> 
<p>如上面代码中&#xff0c;我们可以得到各种k加到图片像素点上后的图片像素平均值</p> 
<p><img alt="" height="179" src="https://img-blog.csdnimg.cn/3660d859516441b192c028bebd81f524.png" width="250" /></p> 
<p>上面测试代码结果显示&#xff0c;k取14时&#xff0c;老图片像素点的平均值为128.2&#xff0c;最接近中位值128。</p> 
<p></p> 
<p>上面算法时间复杂度是外层256&#xff0c;内层100&#xff08;1 &lt;&#61; n &lt;&#61; 100&#xff09;&#xff0c;差不多两三万次循环&#xff0c;可以接受。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on(&#34;line&#34;, (line) &#61;&gt; {
  const arr &#61; line.split(&#34; &#34;).map(Number);
  console.log(getResult(arr));
});

function getResult(arr) {
  const len &#61; arr.length;
  let minDiff &#61; Infinity;
  let ans;

  for (let k &#61; -127; k &lt;&#61; 128; k&#43;&#43;) {
    let sum &#61; 0;
    for (let j &#61; 0; j &lt; len; j&#43;&#43;) {
      let newVal &#61; arr[j] &#43; k;
      // 新图的像素值会自动截取到[0,255]范围。当新像素值&lt;0&#xff0c;其值会更改为0&#xff1b;当新像素值&gt;255&#xff0c;其值会更改为255&#xff1b;
      newVal &#61; newVal &lt; 0 ? 0 : newVal &gt; 255 ? 255 : newVal;
      sum &#43;&#61; newVal;
    }

    const diff &#61; Math.abs(sum / len - 128);

    if (diff &lt; minDiff) {
      minDiff &#61; diff;
      ans &#61; k;
    } else if (diff &#61;&#61;&#61; minDiff) {
      // 如有多个整数k都满足&#xff0c;输出小的那个k
      ans &#61; Math.min(ans, k);
    }
  }

  return ans;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    String str &#61; sc.nextLine();
    Integer[] arr &#61; Arrays.stream(str.split(&#34; &#34;)).map(Integer::parseInt).toArray(Integer[]::new);

    System.out.println(getResult(arr));
  }

  public static int getResult(Integer[] arr) {
    int len &#61; arr.length;
    double minDiff &#61; Integer.MAX_VALUE;
    Integer ans &#61; null;

    for (int k &#61; -127; k &lt;&#61; 128; k&#43;&#43;) {
      double sum &#61; 0;
      for (Integer val : arr) {
        int newVal &#61; val &#43; k;
        // 新图的像素值会自动截取到[0,255]范围。当新像素值&lt;0&#xff0c;其值会更改为0&#xff1b;当新像素值&gt;255&#xff0c;其值会更改为255&#xff1b;
        newVal &#61; Math.max(0, Math.min(newVal, 255));
        sum &#43;&#61; newVal;
      }

      double diff &#61; Math.abs(sum / len - 128);

      if (diff &lt; minDiff) {
        minDiff &#61; diff;
        ans &#61; k;
      } else if (diff &#61;&#61; minDiff &amp;&amp; ans !&#61; null) {
        // 如有多个整数k都满足&#xff0c;输出小的那个k
        ans &#61; Math.min(ans, k);
      }
    }

    return ans;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python">import sys

# 输入获取
arr &#61; list(map(int, input().split()))


# 算法入口
def getResult(arr):
    minDiff &#61; sys.maxsize
    ans &#61; None

    for k in range(-127, 129):
        sum &#61; 0
        for j in range(len(arr)):
            # 新图的像素值会自动截取到[0,255]范围。当新像素值&lt;0&#xff0c;其值会更改为0&#xff1b;当新像素值&gt;255&#xff0c;其值会更改为255&#xff1b;
            newVal &#61; min(max(0, arr[j] &#43; k), 255)
            sum &#43;&#61; newVal

        diff &#61; abs(sum / len(arr) - 128)

        if diff &lt; minDiff:
            minDiff &#61; diff
            ans &#61; k
        elif diff &#61;&#61; minDiff and ans is not None:
            # 如有多个整数k都满足&#xff0c;输出小的那个k
            ans &#61; min(ans, k)

    return ans


# 算法调用
print(getResult(arr))
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>